import { track, trigger } from './effect'

//只需在初始话的时候创建就行了
const get = createGetter()
const set = createSetter()
const readonlyGet = createGetter(true)

/**
 * @description: 创建get高阶函数
 * @param {*} isReadonly
 * @return {*}
 */
function createGetter(isReadonly = false) {
  return function get(target, key) {
    const res = Reflect.get(target, key)

    if (!isReadonly) {
      // TODO: 依赖收集
      track(target, key)
    }
    return res
  }
}

/**
 * @description:创建set高阶函数
 * @param {*} isReadonly
 * @return {*}
 */
function createSetter(isReadonly = false) {
  return function set(target, key, value) {
    const res = Reflect.set(target, key, value)

    // TODO:  触发依赖
    trigger(target, key)
    return res
  }
}

/**
 * @description: reactive的描述
 * @return {*}
 */
export const mutableHandlers = {
  get,
  set
}

/**
 * @description: readonly的描述
 * @return {*}
 */
export const readonlyHandlers = {
  get: readonlyGet,
  set(target, key, value) {
    console.warn(`key:${key} set 失败 因为target 是readyOnly`, target)

    return true
  }
}
